<template>
  <div class="container">
    <div class="app-container">
      <el-tree
        :props="{ label:'name'}"
        :data="list"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{data}">
          <el-row style="width:100%" type="flex" justify="space-between">
            <el-col>
              <span>{{ data.name }}</span>
            </el-col>
            <el-col style="width: 140px;">
              <span style="margin:0 20px">管理员</span>
              <el-dropdown @command="fn($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>

      </el-tree>

    </div>
    <!-- 3、定义部门ref -->
    <add-dep ref="depRef" v-model="visible" :pid="pid" @onSuccess="onLoad" />
    <!-- <add-dep :visible="visible" @xxx="visible=$event" /> -->
  </div>
</template>
<script>
import { delDepAPI, getDepartMentAPI } from '@/api/department'
import { list2Tree } from '@/utils/index'
import addDep from './components/add-dep.vue'
export default {
  name: 'Department',
  components: { addDep },
  data() {
    return {
      list: [],
      visible: false,
      pid: null

    }
  },
  created() {
    this.onLoad()
  },
  methods: {
    async fn(type, id) {
      if (type === 'add') {
        // TODO 做新增
        this.visible = true
        this.pid = id
      }
      if (type === 'edit') {
        // TODO 做编辑
        this.visible = true
        // 4、ref获取数据
        this.$refs.depRef.onDetail(id)
        this.$refs.depRef.formData.id = id
      }
      if (type === 'del') {
        // TODO 做删除
        await this.$confirm('确认删除吗')
        await delDepAPI(id)
        this.$message.success('删除成功')
        this.onLoad()
      }
    },
    async onLoad() {
      const res = await getDepartMentAPI()
      const tree = list2Tree(res.data, 0)
      this.list = tree
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}
</style>
